'use strict';

const Controller = require('egg').Controller;

class WearRecordController extends Controller {
  // 获取穿搭记录列表
  async index() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      // 现在可以使用Sequelize ORM，因为已经修复了deleted_at字段配置
      const records = await ctx.model.WearRecord.findAll({
        where: { user_id: userId },
        include: [{
          model: ctx.model.Outfit,
          as: 'outfit',
          attributes: ['name', 'main_image'],
          required: false, // LEFT JOIN
        }],
        order: [['wear_date', 'DESC']],
        // Sequelize会自动处理软删除，只返回deleted_at为null的记录
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: records,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取穿搭记录详情
  async show() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;
    const recordId = ctx.params.id;

    try {
      const record = await ctx.model.WearRecord.findOne({
        where: { id: recordId, user_id: userId },
        include: [
          {
            model: ctx.model.Outfit,
            as: 'outfit',
          },
        ],
      });

      if (!record) {
        ctx.throw(404, '记录不存在');
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: record,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 创建穿搭记录
  async create() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;

    ctx.validate({
      wear_date: { type: 'date', required: true },
      outfit_id: { type: 'int', required: false },
    });

    try {
      const recordData = {
        ...ctx.request.body,
        user_id: userId,
      };

      const record = await ctx.model.WearRecord.create(recordData);

      // 如果有关联的搭配，更新搭配的穿着统计
      if (recordData.outfit_id) {
        await this.updateOutfitStats(recordData.outfit_id, recordData.wear_date);
      }

      ctx.body = {
        code: 200,
        message: '创建成功',
        data: record,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新搭配统计信息
  async updateOutfitStats(outfitId, wearDate) {
    const { ctx } = this;

    try {
      // 获取该搭配的穿着次数
      const wearCount = await ctx.model.WearRecord.count({
        where: { outfit_id: outfitId }
      });

      // 更新搭配的穿着次数和最后穿着日期
      await ctx.model.Outfit.update({
        wear_count: wearCount,
        last_worn_date: wearDate
      }, {
        where: { id: outfitId }
      });
    } catch (error) {
      console.error('更新搭配统计失败:', error);
      // 不抛出错误，避免影响主流程
    }
  }

  // 更新穿搭记录
  async update() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;
    const recordId = ctx.params.id;

    try {
      const record = await ctx.model.WearRecord.findOne({
        where: { id: recordId, user_id: userId },
      });

      if (!record) {
        ctx.throw(404, '记录不存在');
      }

      const oldOutfitId = record.outfit_id;
      const updateData = ctx.request.body;
      const newOutfitId = updateData.outfit_id;

      await ctx.model.WearRecord.update(updateData, {
        where: { id: recordId },
      });

      // 如果搭配ID发生变化，需要更新两个搭配的统计
      if (oldOutfitId !== newOutfitId) {
        if (oldOutfitId) {
          await this.recalculateOutfitStats(oldOutfitId);
        }
        if (newOutfitId) {
          await this.recalculateOutfitStats(newOutfitId);
        }
      } else if (newOutfitId) {
        // 如果搭配ID没变但有搭配关联，重新计算统计（可能日期变了）
        await this.recalculateOutfitStats(newOutfitId);
      }

      ctx.body = {
        code: 200,
        message: '更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除穿搭记录
  async destroy() {
    const { ctx } = this;
    const userId = ctx.state.user?.id || 1;
    const recordId = ctx.params.id;

    try {
      const record = await ctx.model.WearRecord.findOne({
        where: { id: recordId, user_id: userId },
      });

      if (!record) {
        ctx.throw(404, '记录不存在');
      }

      const outfitId = record.outfit_id;

      await ctx.model.WearRecord.destroy({
        where: { id: recordId },
      });

      // 如果有关联的搭配，重新计算搭配统计
      if (outfitId) {
        await this.recalculateOutfitStats(outfitId);
      }

      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 重新计算搭配统计信息
  async recalculateOutfitStats(outfitId) {
    const { ctx } = this;

    try {
      // 获取该搭配的所有穿着记录
      const wearRecords = await ctx.model.WearRecord.findAll({
        where: { outfit_id: outfitId },
        order: [['wear_date', 'DESC']]
      });

      const wearCount = wearRecords.length;
      const lastWornDate = wearCount > 0 ? wearRecords[0].wear_date : null;

      // 更新搭配的穿着次数和最后穿着日期
      await ctx.model.Outfit.update({
        wear_count: wearCount,
        last_worn_date: lastWornDate
      }, {
        where: { id: outfitId }
      });
    } catch (error) {
      console.error('重新计算搭配统计失败:', error);
      // 不抛出错误，避免影响主流程
    }
  }
}

module.exports = WearRecordController;
